﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using NHibernate;
using NHibernate.Linq;
using dbPoll_Application.Helpers;
using NHibernate.Criterion;

namespace dbPoll_Application.Models
{
    public static class PollRepository
    {
        public static Poll GetPollByID(int pollID)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            var poll = (from item in session.Query<Poll>()
                        where item.pollID == pollID
                        select item).FirstOrDefault<Poll>();
            return poll;
        }

        public static Poll GetPollContainingQuestion(Question question)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            var poll = (from item in session.Query<Poll>()
                        where item.questions.Contains(question)
                        select item).FirstOrDefault<Poll>();
            return poll;
        }

        public static Boolean UpdatePoll(Poll poll)
        {
            ITransaction transaction = null;
            try
            {
                ISession session = NHibernateHelper.GetCurrentSession();
                using (transaction = session.BeginTransaction())
                {
                    session.SaveOrUpdate(poll);
                    transaction.Commit();
                    return transaction.WasCommitted;
                }
            }
            catch (Exception e)
            {
                if (transaction != null)
                {
                    transaction.Rollback();
                }
            }
            return false;
        }

        public static IList<Poll> GetAllPolls()
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            var poll = (from item in session.Query<Poll>()
                        select item).ToList<Poll>();
            return poll;
        }

        public static IList<Poll> GetPollContainingParticipant(Participant participant)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            var poll = (from item in session.Query<Poll>()
                        where item.participants.Contains(participant)
                        select item).ToList<Poll>();
            return poll;
        }

        public static IList<Poll> GetPollsMasteredBy(User user)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            var polls = (from item in session.Query<Poll>()
                         where item.pollMasters.Contains(user)
                         select item).ToList<Poll>();
            return polls;
        }
    }
}
